<script setup lang="ts">
import type { VxeGridProps } from 'vxe-table'
import { SearchTable } from '@fl/components'
import { addSnapshot, getSnapshotList, pageByGroupSnapshotId } from '@fl/api/advertising-api'
import { cloneDeep } from 'lodash-es'

const id = defineModel<number>('id', { required: false })
const show = defineModel<boolean>('show', { required: true })
const emits = defineEmits(['update:show', 'confirm'])

const records = ref<any>()
const tableHeight = ref<number>(420)
const isLoading = ref<boolean>(false)
const timeList = ref<any>()
const currentTime = ref<number>(0)
const loading = ref<boolean>(false)
const selectGroupSnapshotId = ref<number>()
const initialPage = {
    currentPage: 1,
    pageSize: 5,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))


watchEffect(() => {
    if (id.value) {
        getTimeList()
    }
})

// 分页
const handlePageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    getAdList(selectGroupSnapshotId.value)
}

// 获取分期列表以及默认选中第一条
function getTimeList() {
    loading.value = true
    getSnapshotList({
        groupId: id.value,
    }).then((data) => {
        loading.value = false
        // data有数据说明已存在广告排期
        if (data.length) {
            timeList.value = data.map(item => ({
                ...item,
                activeTime: [item.activeStart, item.activeEnd],
            }))
            selectTime(0, timeList.value[0])
        }
        else {
            timeList.value = [{
                activeTime: [],
                groupId: id.value,
            }]
            records.value = []
        }
    }).catch(() => {
        loading.value = false
    })
}

// 选择分期
function selectTime(index, item) {
    currentTime.value = index
    selectGroupSnapshotId.value = item.id
    item.id && getAdList(item.id)
}

// 获取分期下的广告列表
function getAdList(id) {
    isLoading.value = true
    pageByGroupSnapshotId({
        groupSnapshotId: id,
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
    }).then((res) => {
        isLoading.value = false
        // 考虑非第一页刚好只有一条被删除的情况
        if (tablePage.value.currentPage !== 1 && !res.rows?.length) {
            tablePage.value.currentPage--
            getAdList(id)
            return
        }
        records.value = res.rows
        tablePage.value.total = res.total
    }).catch(() => {
        isLoading.value = false
    })
}

// 设置分期时间
async function changeTime(val, item, index) {
    await addSnapshot({
        activeEnd: val[1],
        activeStart: val[0],
        groupId: id.value,
    }).then((res) => {
        item.activeTime = [res.activeStart, res.activeEnd]
        item.id = res.id
    }).catch(() => {
        item.activeTime = []
    })
    selectTime(index, item)
}

function submit() {
    emits('update:show', false)
    emits('confirm', id.value)
}

function goBack() {
    emits('update:show', false)
    console.log('取消')
}

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'imgUri', slots: { default: 'imgUri' }, title: '图片', width: '120' },
        { field: 'headIconUri', slots: { default: 'headIconUri' }, title: '头角标' },
        { field: 'footIconUri', slots: { default: 'footIconUri' }, title: '尾巴角标' },
        { field: 'linkType', title: '链接类型', width: 80 },
        { field: 'businessType', title: '业务类型', width: 80 },
        { field: 'title', title: '楼盘/产品名称', width: 120 },
        { field: 'forwardUrl', title: '链接' },
        // { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 220 },
    ],
})
</script>

<template>
    <PlusDialog v-model="show" :title="'选择广告组'" width="1000" @close="goBack" :has-footer="false">
        <!-- <ElSkeleton v-if="isLoading" :rows="5" /> -->

        <div class="ad-by-stages">
            <div v-for="(item, index) in timeList" :key="item.adTime" class="time-item">
                <div :class="currentTime === index ? 'ad-time-piker active' : 'ad-time-piker'">
                    <el-date-picker v-model="item.activeTime" type="datetimerange" start-placeholder="开始日期"
                        end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                        @change="(val) => changeTime(val, item, index)" disabled />

                    <span :class="currentTime === index ? 'sort active' : 'sort'" @click="selectTime(index, item)">
                        {{ index + 1 }}
                    </span>
                </div>
            </div>
        </div>

        <SearchTable v-bind="gridOptions" v-model:pager="tablePage" :loading="isLoading" :data="records"
            :row-config="{ height: 120 }" :height="tableHeight" @page-change="handlePageChange">
            <template #imgUri="row">
                <el-image v-if="row.row.imgUri" style="width: 80x; height: 80x" :src="row.row.imgUri" :zoom-rate="1.2"
                    :max-scale="7" :min-scale="0.2" :preview-src-list="[row.row.imgUri]" :initial-index="4"
                    fit="contain" />
            </template>

            <template #headIconUri="row">
                <el-image v-if="row.row.headIconUri" style="width: 80x; height: 80x" :src="row.row.headIconUri"
                    :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[row.row.headIconUri]"
                    :initial-index="4" fit="contain" />
            </template>

            <template #footIconUri="row">
                <el-image v-if="row.row.footIconUri" style="width: 80x; height: 80x" :src="row.row.footIconUri"
                    :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[row.row.footIconUri]"
                    :initial-index="4" fit="contain" />

            </template>
        </SearchTable>

        <div class="mt30" style="text-align: center">
            <el-button @click="goBack">
                返回上一级
            </el-button>
            <el-button type="primary" @click="submit">
                选择此组
            </el-button>
        </div>

    </PlusDialog>

</template>

<style lang="scss" scoped>
.ad-by-stages {
    display: flex;
    flex-wrap: wrap;

    .time-item {
        display: flex;
        width: 310px;
        margin-bottom: 12px;

        :deep(.ad-time-piker) {
            display: flex;
            align-items: center;
            position: relative;

            >.sort {
                position: absolute;
                left: 0;
                top: 0;
                width: 30px;
                height: 32px;
                display: block;
                font-size: 16px;
                line-height: 32px;
                border-right: 1px solid #e6ebf5;
                text-align: center;
                cursor: pointer;

                &.active {
                    color: var(--el-color-primary);
                    border-right: 1px solid var(--el-color-primary);
                }
            }

            &.active {
                .el-range-editor.el-input__wrapper {
                    border: 1px solid var(--el-color-primary);
                }
            }
        }

        :deep(.el-range-editor.el-input__wrapper) {
            width: 260px;
            padding-left: 40px;
        }

        .icon-btns {
            display: flex;
            align-items: center;
            margin-left: 10px;

            .el-icon {
                font-size: 18px;
                cursor: pointer;

                &.add {
                    color: var(--el-color-primary);
                    margin-right: 6px;
                }
            }
        }
    }
}
</style>
